package com.xiaomi.web.handlers;

import com.github.pagehelper.PageInfo;
import com.xiaomi.domain.UserEntity;
import com.xiaomi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminHandler {
    @Autowired
    UserService userService;

    @RequestMapping("/findPageUsers")
    public String getUsers(@RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        if (pageNum <= 0) pageNum = 1;
        PageInfo<UserEntity> pageInfo = userService.findPageUsers(pageNum);//固定每页显示5条

        model.addAttribute("pageInfo", pageInfo);
        return "admin/user_list";
    }

    @RequestMapping("/deleteUsersById")
    public String deleteUsersById(String[] ids, Integer pageNum, Model model) {
        boolean flag = userService.deleteUsersById(ids);
        if (flag == false) {
            return "admin/error";
        }
        PageInfo<UserEntity> pageInfo = userService.findPageUsers(pageNum);//固定每页显示5条

        model.addAttribute("pageInfo", pageInfo);
        return "admin/user_list";
    }

    @RequestMapping("/updateManager")
    public String updateManager(String uid, Integer manager, Integer pageNum, Model model) {
        boolean flag = userService.updateManager(uid, manager);
        if (flag == false) {
            return "admin/error";
        }
        PageInfo<UserEntity> pageInfo = userService.findPageUsers(pageNum);//固定每页显示5条

        model.addAttribute("pageInfo", pageInfo);
        return "admin/user_list";
    }

    @ResponseBody
    @RequestMapping("/login")
    public boolean login(String username, String password, HttpServletRequest request) {
        UserEntity admin = userService.getUserByUsernamePwd(username, password);
        if (admin == null) {
            return false;
        } else {
            request.getSession().setAttribute("admin", admin);
            return true;
        }
    }
}
